#include<iostream>
#include<unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include<cstring>
#include<cerrno>

using namespace std;

int main()
{
    int pipefd[2];
    if(pipe(pipefd)<0)
    {
        cout<<strerror(errno);
    }

    int id=fork();
    if(id<0)
    {
        cout<<"fork err"<<endl;
        exit(2);
    }
    else if(id==0)//子进程
    {
        cout<<"进入子进程"<<endl;
        close(pipefd[1]);
        char getbuf[1024];
        memset(getbuf,0,sizeof(getbuf));
        cout<<"子进程读取"<<endl;
        ssize_t s = read(pipefd[0],getbuf,sizeof(getbuf)-1);
        if(s>0)
        {
            //读取成功
            getbuf[s]='\0';
            cout<<"子进程收到的消息是"<<getbuf<<endl;
        }
        else if(s==0)
        {
            cout << "父进程写完了，我也退出啦" << endl;
            exit(2);
        }
        else{}
        cout<<"关闭子进程读端"<<endl;
        close(pipefd[0]);
    }
    else
    {
        cout<<"进入父进程"<<endl;
        close(pipefd[0]);
        const char* buf="i am father";
        cout<<"父进程写入"<<endl;
        write(pipefd[1],buf,strlen(buf));
        cout<<"父进程写完了,关闭父进程"<<endl;
        close(pipefd[1]);
        pid_t ret=waitpid(id,nullptr,0);
        if(ret>0)
        {
            cout<<"等待子进程成功"<<endl;
        }
        else
        {
            cout<<"等待子进程失败"<<endl;
            exit(-1);
        }
    }
    return 0;
}